package com.mobile.check.util;

import java.io.File;
import java.util.List;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.kit.NLog;
import cn.droidlover.xdroidmvp.net.XApi;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import com.mobile.check.activitys.GlobalPoolApplication;
import com.mobile.check.beans.TaskInfo;
import com.mobile.check.beans.UploadFileResponse;
import com.mobile.check.db.EntityManager;
import com.mobile.check.net.Api;
import com.mobile.check.net.BaseObjBean;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 类名: ExprotListPresent
 * 作者: 李学伟
 * 日期: 2020年09月30日 10:26
 * 描述:
 */
public class UploadHelper {
    UploadListener uploadListener;

    public UploadHelper(UploadListener uploadListener) {
        this.uploadListener = uploadListener;
    }

    private Observable getUploadObservable(final TaskInfo taskInfo) {
        Observable<UploadFileResponse> xlsObservable = getFileObservable(taskInfo.getTaskFilePath());
        return xlsObservable.flatMap(new Function<UploadFileResponse, ObservableSource<BaseObjBean>>() {
            @Override
            public ObservableSource<BaseObjBean> apply(UploadFileResponse uploadFileResponse) throws Exception {
                if (!taskInfo.isRepeatTask()) {
                    return Api.getApiService().passback(getToken(), (int) taskInfo.getId(), uploadFileResponse.getId());
                } else {
                    return Api.getApiService().re_passback(getToken(), (int) taskInfo.getId(), uploadFileResponse.getId());
                }
            }
        }).map(new Function<BaseObjBean, Boolean>() {
            @Override
            public Boolean apply(BaseObjBean baseObjBean) throws Exception {
                if (baseObjBean.getCode() == 1) {
                    taskInfo.setHadUploaded(true);
                    EntityManager.getInstance().saveTaskInfo(taskInfo);
                }
                return baseObjBean.getCode() == 1;
            }
        });

//                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<BaseObjBean>() {
//            @Override
//            public void accept(BaseObjBean baseObjBean) throws Exception {
//                if (baseObjBean.getCode() == 1) {
//                    taskInfo.setHadUploaded(true);
//                    EntityManager.getInstance().saveTaskInfo(taskInfo);
//                    uploadListener.uploadSuccess();
//                } else {
//                    uploadListener.uploadFail(baseObjBean.getCode(), baseObjBean.getMessage());
//                }
//            }
//        }, new Consumer<Throwable>() {
//            @Override
//            public void accept(Throwable throwable) throws Exception {
//                throwable.printStackTrace();
//                uploadListener.uploadFail(0, "上传失败");
//            }
//        });
    }


    public void startUpload(List<TaskInfo> list) {
        final int count = list.size();
        Observable[] upLoadList = new Observable[list.size()];
        for (TaskInfo taskInfo : list) {
            Observable uploadObservable = getUploadObservable(taskInfo);
            upLoadList[list.indexOf(taskInfo)] = uploadObservable;
        }
        Observable.mergeArray(upLoadList).map(new Function<Boolean, Boolean>() {
            @Override
            public Boolean apply(Boolean o) throws Exception {
                NLog.d("startUpload", "accept111-o=" + o);
                return o;
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer() {
            @Override
            public void accept(Object o) throws Exception {
                NLog.d("startUpload", "accept-o=" + o);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        }, new Action() {
            @Override
            public void run() throws Exception {
                NLog.d("startUpload", "上传完成");
                uploadListener.uploadSuccess();
            }
        });

    }

    private Observable<UploadFileResponse> getFileObservable(String filePath) {
        MultipartBody xlsBody = filesToMultipartBody(getToken(), filePath, "");
        return Api.getApiService().uploadFileWithRequestBody(xlsBody)
                .compose(XApi.<BaseObjBean<UploadFileResponse>>getApiTransformer())
                .flatMap(new Function<BaseObjBean<UploadFileResponse>, ObservableSource<UploadFileResponse>>() {
                    @Override
                    public ObservableSource<UploadFileResponse> apply(BaseObjBean<UploadFileResponse> bean) throws Exception {
                        return Observable.just(bean.getData());
                    }
                });
    }

    public static MultipartBody filesToMultipartBody(String token, String path, String fileType) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        File file = new File(path);
        String mediaType;
        switch (fileType) {
            case "xls":
                mediaType = "application/x-xls";
                break;
            case "zip":
                mediaType = "application/zip";
                break;
            case "jpeg":
                mediaType = "image/jpeg";
                break;
            default:
                mediaType = "application/octet-stream";
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse(mediaType), file);
        builder.addFormDataPart("file", file.getName(), requestBody);
        builder.addFormDataPart("token", token);
        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }

    public String getToken() {
        String token = SharedPref.getInstance(GlobalPoolApplication.getContext()).getString(AppContents.TOKEN, "");
        return token;
    }

    public interface UploadListener {
        void uploadSuccess();

        void uploadFail(int code, String message);
    }
}
